package com.xinyue.cross.server.client;

import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageEncodeHandler extends ChannelOutboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(MessageEncodeHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        GameServerMessageModel<GameServerRequestHeader> messageModel = (GameServerMessageModel<GameServerRequestHeader>) msg;
        // 4 字节是消息完整大小所点的位数
        int totalSize = messageModel.getHeader().getHeaderTotalSize() + 4;
        if (messageModel.getBody() != null) {
            totalSize += messageModel.getBody().readableBytes();
        }
        ByteBuf byteBuf = Unpooled.buffer(totalSize);
        byteBuf.writeInt(totalSize);
        messageModel.getHeader().write(byteBuf);

        if (messageModel.getBody() == null) {
            ctx.writeAndFlush(byteBuf);
        } else {
            ByteBuf newByteBuf = Unpooled.wrappedBuffer(byteBuf, messageModel.getBody().slice());
            ctx.writeAndFlush(newByteBuf);
        }
        logger.debug("服务客户端发送消息,size: {},header-> {}", totalSize, messageModel.getHeader());
    }


}
